package com.example.wlzz.controller.admin;

import com.example.wlzz.constant.CookiesConstant;
import com.example.wlzz.constant.RedisConstant;
import com.example.wlzz.controller.UserController;
import com.example.wlzz.enums.ResultEnum;
import com.example.wlzz.form.RegisterForm;
import com.example.wlzz.service.AdminService;
import com.example.wlzz.service.UserService;
import com.example.wlzz.utils.CookieUtil;
import com.example.wlzz.utils.PhoneUtil;
import com.example.wlzz.utils.ResultVOUtil;
import com.example.wlzz.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/backstage")
@Slf4j
@ApiIgnore
public class AdminIndexController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @GetMapping("/login")
    public ModelAndView login(){
        return new ModelAndView("/login");
    }
    @PostMapping("/userLogin")
    @ResponseBody
    public ResultVO userLogin(@Valid RegisterForm userForm , BindingResult bindingResult,
                              HttpServletResponse response){
        if(bindingResult.hasErrors()) {
            log.warn("userForm={}",userForm);
            return ResultVOUtil.error(ResultEnum.LOGIN_ERROR.getCode(),ResultEnum.LOGIN_ERROR.getMessage());
        }
        if(!PhoneUtil.getRightPhone(userForm.getPhone())){
            return ResultVOUtil.error(ResultEnum.PHONE_ERROR.getCode(),ResultEnum.PHONE_ERROR.getMessage());
        }
        ResultVO resultVO = adminService.login(userForm);
        if(resultVO.getCode().equals(0)){
            //2. 设置token至redis
            String token = UUID.randomUUID().toString();
            Integer expire = RedisConstant.ADMIN_EXPIRE;
            redisTemplate.opsForValue().set(String.format(RedisConstant.ADMIN_TOKEN_PREFIX, token), userForm.getPhone(), expire, TimeUnit.SECONDS);
            //3. 设置token至cookie
            CookieUtil.set(response, CookiesConstant.ADMIN_TOKEN, token, expire);
            Map<String,Object> map =new HashMap<>();
            map.put("token",token);
            return ResultVOUtil.success(map);
        }else{
            return resultVO;
        }
    }
}
